package vip.xiaonuo.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.core.util.IpAddressUtil;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.deviceset.entity.DwDeviceSet;
import vip.xiaonuo.facedoor.modular.deviceset.service.DwDeviceSetService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.memberdevice.service.MemberDeviceService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.iservice.IMemberDealWithService;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParam;
import vip.xiaonuo.facedoor.iservice.entity.PersonBaseParamRet;
import vip.xiaonuo.facedoor.iservice.issulog.DeviceLogService;
import vip.xiaonuo.facedoor.remote.iservice.adapter.MemberReqAdapter;
import vip.xiaonuo.facedoor.rule.HQRulesEngine;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.AddPersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.DeletePersonRequest;
import vip.xiaonuo.facedoor.vo.dewo.UpdatePersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.HQAddPersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.HQDeletePersonRequest;
import vip.xiaonuo.facedoor.vo.haiqing.RequestHeader;

import java.util.Collections;
import java.util.Objects;
import java.util.Optional;

@Service(RuleConstant.HQ+ RuleConstant.MEMBER_DEAL_WITH)
public class HQMemberDealWithServiceImpl implements IMemberDealWithService {


  @Autowired
  private MemberDeviceService memberDeviceService;

  @Autowired
  private DeviceLogService deviceLogService;

  @Autowired
  private MemberUserService memberUserService;

  @Autowired
  private DwDeviceSetService dwDeviceSetService;


  @Override
  public PersonBaseParamRet getBaseParam(PersonBaseParam personBasePerson) {
    return new PersonBaseParamRet().setUrl("http://" + personBasePerson.getDeviceBase().getCabinetIp() + ":" + personBasePerson.getDeviceBase().getCabinetPort());
  }

  @Override
  public void deleteException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    memberDevice.setFailReason(ExceptionUtils.getMessage(e));
    memberDevice.setStatus(MemberDeviceConstant.DELETE_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, DELETE);
  }

  @Override
  public void delete(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet personBaseParamRet, DeviceBase deviceBase) throws Exception {
    DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
    if (deviceSet==null){
      throw new ServiceException(500,"设置尚未进行配置！");
    }
    HQDeletePersonRequest hqDeletePersonRequest = new HQDeletePersonRequest();
    HQDeletePersonRequest.InfoDTO infoDTO = new HQDeletePersonRequest.InfoDTO();
    infoDTO.setDeviceID(deviceSet.getDeviceId());
    infoDTO.setIdType(0);
    infoDTO.setTotalNum(1);
    infoDTO.setCustomizeID(Collections.singletonList(Integer.parseInt("1"+memberUser.getId())));
    hqDeletePersonRequest.setInfo(infoDTO);

    DeletePersonRequest deletePersonRequest = new DeletePersonRequest();
    deletePersonRequest.setHqDeletePersonRequest(hqDeletePersonRequest);
    String uri = IFaceDoorDtoService.getBaseParam(
        deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
    String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
    RequestHeader requestHeader = new RequestHeader().setUserName("admin").setPassWord(password);
    deletePersonRequest.setRequestHeader(requestHeader);
    ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.deletePerson(uri, deletePersonRequest);
    memberDeviceService.removeById(memberDevice.getId());
    long count = memberDeviceService.count(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getMemberId, memberUser.getId()));
    if (count == 0 && Objects.equals(memberUser.getDelFlag(), "1")) {
      memberUserService.sendDeleteMessage(memberDevice.getId());
      memberUserService.removeById(memberDevice.getMemberId());
    }
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, DELETE);
  }


  @Override
  public void add(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet personBaseParamRet, DeviceBase deviceBase) throws Exception {
    DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
    if (deviceSet==null){
      throw new ServiceException(500,"设置尚未进行配置！");
    }
    // 获取系统配置
    Integer hqWiegandType = ConstantContextHolder.getSysConfig("HQ_WiegandType", Integer.class, true);
    Integer hq_cardMode = ConstantContextHolder.getSysConfig("HQ_CardMode", Integer.class, true);
    Integer hqRfCardMode = ConstantContextHolder.getSysConfig("HQ_RFCardMode", Integer.class, true);
    Integer hq_id_wg = ConstantContextHolder.getSysConfig("HQ_ID_WG", Integer.class, true);
    AddPersonRequest addPersonRequest = new AddPersonRequest();
    HQAddPersonRequest hqAddPersonRequest = new HQAddPersonRequest();
    HQAddPersonRequest.InfoDTO infoDTO = new HQAddPersonRequest.InfoDTO();
    infoDTO.setDeviceID(deviceSet.getDeviceId());
    infoDTO.setCustomizeID(Integer.parseInt("1"+memberUser.getId()));
    // 白名单
    if (ObjectUtil.equal(memberUser.getPersonType(),0)){
      infoDTO.setPersonType(0);
      // 黑名单
    }else if (ObjectUtil.equal(memberUser.getPersonType(),2)){
      infoDTO.setPersonType(1);
    }
    infoDTO.setName(memberUser.getName());
    infoDTO.setGender(memberUser.getSex()!=null&&memberUser.getSex()==1?0:1);
    infoDTO.setNation(1);
    infoDTO.setIdCard(memberUser.getIdCard());
    infoDTO.setTelnum(memberUser.getTel());
    // 韦根
    if (ObjectUtil.equal(hq_id_wg,0)){
      infoDTO.setMjCardFrom(2);
      infoDTO.setWiegandType(hqWiegandType);
      infoDTO.setWgFacilityCode(memberUser.getWgFacilityCode());
      infoDTO.setMjCardNo(memberUser.getIcCard());
      infoDTO.setCardMode(hq_cardMode);
      // 内置ID卡
    }else if (ObjectUtil.equal(hq_id_wg,1)){
      infoDTO.setRFCardMode(hqRfCardMode);
      infoDTO.setRFIDCard(memberUser.getIcCard());
    }
    infoDTO.setTempvalid(0);
    hqAddPersonRequest.setInfo(infoDTO);
    // 图片转换
    if (StringUtils.isNotBlank(memberUser.getPhoto())){
      hqAddPersonRequest.setPicUri(IpAddressUtil.getImageAddIp(memberUser.getPhoto().replace("\\","/")));

    }else {
      hqAddPersonRequest.setPicUri("");
    }
    String uri = IFaceDoorDtoService.getBaseParam(
        deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
    String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
    addPersonRequest.setHqAddPersonRequest(hqAddPersonRequest).setRequestHeader( new RequestHeader().setUserName("admin").setPassWord(password));
    ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.addPerson(uri, addPersonRequest);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);
    memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
    memberDeviceService.updateById(memberDevice);
  }


  @Override
  public void addException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    // 直接修改为失败
    memberDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
    memberDevice.setStatus(MemberDeviceConstant.ADD_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, ADD);
  }

  @Override
  public void updateException(MemberDevice memberDevice, MemberUser memberUser, DeviceBase deviceBase, Exception e) {
    // 直接修改为失败
    memberDevice.setFailReason(JSON.toJSONString(ExceptionUtils.getMessage(e)));
    memberDevice.setStatus(MemberDeviceConstant.UPDATE_FAIL);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), ExceptionUtils.getMessage(e), FAIL, UPDATE);
  }

  @Override
  public void update(MemberDevice memberDevice, MemberUser memberUser, PersonBaseParamRet baseParam, DeviceBase deviceBase) throws Exception {
    DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, deviceBase.getId()));
    if (deviceSet==null){
      throw new ServiceException(500,"设置尚未进行配置！");
    }
    // 获取系统配置
    Integer hqWiegandType = ConstantContextHolder.getSysConfig("HQ_WiegandType", Integer.class, true);
    Integer hq_cardMode = ConstantContextHolder.getSysConfig("HQ_CardMode", Integer.class, true);
    Integer hqRfCardMode = ConstantContextHolder.getSysConfig("HQ_RFCardMode", Integer.class, true);
    Integer hq_id_wg = ConstantContextHolder.getSysConfig("HQ_ID_WG", Integer.class, true);
    UpdatePersonRequest addPersonRequest = new UpdatePersonRequest();
    HQAddPersonRequest hqAddPersonRequest = new HQAddPersonRequest();
    HQAddPersonRequest.InfoDTO infoDTO = new HQAddPersonRequest.InfoDTO();
    infoDTO.setDeviceID(deviceSet.getDeviceId());
    infoDTO.setCustomizeID(Integer.parseInt("1"+memberUser.getId()));
    // 白名单
    if (ObjectUtil.equal(memberUser.getPersonType(),0)){
      infoDTO.setPersonType(0);
      // 黑名单
    }else if (ObjectUtil.equal(memberUser.getPersonType(),2)){
      infoDTO.setPersonType(1);
    }
    infoDTO.setName(memberUser.getName());
    infoDTO.setGender(memberUser.getSex()!=null&&memberUser.getSex()==1?0:1);
    infoDTO.setNation(1);
    infoDTO.setIdCard(memberUser.getIdCard());
    infoDTO.setTelnum(memberUser.getTel());
    // 韦根
    if (ObjectUtil.equal(hq_id_wg,0)){
      infoDTO.setMjCardFrom(2);
      infoDTO.setWiegandType(hqWiegandType);
      infoDTO.setWgFacilityCode(memberUser.getWgFacilityCode());
      infoDTO.setMjCardNo(memberUser.getIcCard());
      infoDTO.setCardMode(hq_cardMode);
      // 内置ID卡
    }else if (ObjectUtil.equal(hq_id_wg,1)){
      infoDTO.setRFCardMode(hqRfCardMode);
      infoDTO.setRFIDCard(memberUser.getIcCard());
    }
    infoDTO.setTempvalid(0);
    hqAddPersonRequest.setInfo(infoDTO);
    // 图片转换
    if (StringUtils.isNotBlank(memberUser.getPhoto())){
      hqAddPersonRequest.setPicUri(IpAddressUtil.getImageAddIp(memberUser.getPhoto().replace("\\","/")));
    }else {
      hqAddPersonRequest.setPicUri("");
    }
    String uri = IFaceDoorDtoService.getBaseParam(
        deviceBase.getCabinetIp(), Integer.parseInt(deviceBase.getCabinetPort()));
    String password = Optional.ofNullable(deviceBase.getDevicePassword()).orElse("admin");
    addPersonRequest.setHqAddPersonRequest(hqAddPersonRequest).setRequestHeader( new RequestHeader().setUserName("admin").setPassWord(password));
    ReturnJson returnJson = HQRulesEngine.faceDoorDtoService.updatePerson(uri, addPersonRequest);
    if (ObjectUtil.equal(returnJson.getCode(),"477")){
      throw new ServiceException(500,"请更换人员图片!");
    }
    memberDevice.setStatus(MemberDeviceConstant.SYNC_SUCCESS);
    memberDeviceService.updateById(memberDevice);
    deviceLogService.addMemberLog(memberUser.getName(), deviceBase.getName(), JSON.toJSONString(returnJson), SUCCESS, ADD);
  }
}
